//
//  LSHomeVController.m
//  LookScore
//
//  Created by wr on 2017/12/5.
//  Copyright © 2017年 ChongQingXunTiCompany. All rights reserved.
//
#import "LSHttpEnclosureTool.h"
#import "LSHomeVController.h"
#import "LSLoginVController.h"
#import "LSNavigationViewController.h"
#import "LSMineVController.h"
#import "LSRegisterVController.h"
#import "LSLoginVController.h"
#import "LSSetNickNameVController.h"
#import "LSHomeHotMatchCell.h"
#import "LSHomeSectionCell.h"
#import "LSCustomHeaderView.h"
#import <SDCycleScrollView.h>
#import "LSHomeCustomFunctionView.h"
#import <MJRefresh.h>
#import "LSHomeArticleHotModel.h"
#import "LSHomeHotMatchModel.h"
#import "LSHomeArticleDetailVController.h"
#import "LSDataBankVController.h"
#import "LSSocketManeger.h"
#import "LSExpertRankBaseViewController.h"
#import "LSPlayTricksViewController.h"
#import "LSHotTopicViewController.h"
//#import "ConversationDetailController.h"
//#import "CWScrollView.h"
//#import "UIViewController+CWLateralSlide.h"
#import "LSLiveCompetitionViewController.h"

#import "LSRefreshHeaderView.h"

#import "WRNavigationBar.h"
#import "XYSideViewController.h"



#define NAVBAR_COLORCHANGE_POINT (IMAGE_HEIGHT - NAV_HEIGHT*2)
#define IMAGE_HEIGHT 220
#define NAV_HEIGHT 64

@interface LSHomeVController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UIGestureRecognizerDelegate>

@property(strong,nonatomic)UIButton *mineCenterBtn;

@property(strong,nonatomic)UITableView *tableView;

@property(assign,nonatomic)NSInteger  pageIndex;

@property(assign,nonatomic)NSInteger  queryType;//0推荐 1热门

@property(strong,nonatomic)NSMutableArray *modelArray;

@property(strong,nonatomic)NSMutableArray *hotMatchArray;

@property(strong,nonatomic)NSMutableArray *matchSocketArray;

@property(strong,nonatomic)NSMutableArray *bannerArray;

@property(strong,nonatomic)NSMutableArray *sectionArray;

@property(strong,nonatomic)SDCycleScrollView *cycleScrollView;

@property (nonatomic, assign) NSInteger tag;

@end

@implementation LSHomeVController{
    LSSocketManeger * manager;
    LSMineVController *mineVC;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
//    [notifiCenter addObserver:self selector:@selector(updateInfo) name:@"LOADCIRCLEDATA" object:nil];
    
//    if ([LSAccountArchive isLogin]) {
//        LSMineVController *mine = [[LSMineVController alloc] init];
//        [mine getUserInfo];
//    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [JANALYTICSService startLogPageView:@"first_page_flow"];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [JANALYTICSService stopLogPageView:@"first_page_flow"];
}

-(UITableView *)tableView{
    if (!_tableView) {

        CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        _tableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 0;
        
        
        _tableView.contentInset = UIEdgeInsetsMake(-[self navBarBottom], 0, 0, 0);
//        if (@available(iOS 11.0, *)) {
//            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//        } else {
//            self.automaticallyAdjustsScrollViewInsets = NO;
//        }
        _tableView.backgroundColor =LSBackGroundColor;
//        _tableView.showsVerticalScrollIndicator = NO;
       
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (int)navBarBottom
{
    if ([WRNavigationBar isIphoneX]) {
        return 88;
    } else {
        return 64;
    }
}
//- (UIButton *)mineCenterBtn{
//    if (!_mineCenterBtn) {
//        _mineCenterBtn = [[UIButton alloc] init];
//        [_mineCenterBtn addTarget:self action:@selector(clickMineCenterButton) forControlEvents:UIControlEventTouchUpInside];
//        [_mineCenterBtn setBackgroundImage:[UIImage imageNamed:@"MineCenter"] forState:UIControlStateNormal];
//    }
//    return _mineCenterBtn;
//}
- (NSMutableArray *)modelArray{
    if (!_modelArray) {
        _modelArray = @[].mutableCopy;
    }
    return _modelArray;
}
- (NSMutableArray *)hotMatchArray{
    if (!_hotMatchArray) {
        _hotMatchArray = [NSMutableArray array];
    }
    return _hotMatchArray;
}
- (NSMutableArray *)matchSocketArray{
    if (!_matchSocketArray) {
        _matchSocketArray = [NSMutableArray array];
    }
    return _matchSocketArray;
}
- (NSMutableArray *)bannerArray{
    
    if (!_bannerArray) {
        _bannerArray = @[].mutableCopy;
    }
    return _bannerArray;
}
- (NSMutableArray *)sectionArray{
    if (!_sectionArray) {
        _sectionArray = @[].mutableCopy;
    }
    return _sectionArray;
}
- (void)updateInfo{
    LSMineVController *mine = [[LSMineVController alloc] init];
    [mine getUserInfo];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    self.queryType=0;
    
    self.title = @"";
    [self.tabBarItem setTitle:@"首页"];
    // 设置初始导航栏透明度
    
    [self wr_setNavBarBackgroundAlpha:0];
    

    manager = [LSSocketManeger shareManeger];
    
    


    self.imageArray=@[@"MineCenter(hide)"];//左侧个人中心
    [self.view addSubview:self.tableView];
    [self headView];


//    [self loadData:YES];
//    [self requestBannerData];

//    [self loadSectionData];
    LSRefreshHeaderView *header = [LSRefreshHeaderView headerWithRefreshingBlock:^{
        [self loadSectionData];
        [self loadHotMatchData];
        [self loadData:YES];
        [self requestBannerData];
        
    }];
    self.tableView.mj_header = header;// 设置header
    [header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadData:NO];
    }];
    self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = HOME_INDICATOR_HEIGHT;
}
#pragma mark 🔥 UI
-(void)headView{
    
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, LSAutoVlaue(200, LSScreenWidth))];
    topView.backgroundColor = LSBackGroundColor;
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = LSTitleWhiteColor;
    [topView addSubview:backView];
    backView.sd_layout
    .leftEqualToView(topView)
    .topEqualToView(topView)
    .rightEqualToView(topView)
    .bottomEqualToView(topView).offset(-9);
    
    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero
                                                          delegate:self
                                                  placeholderImage:[UIImage imageNamed:@"轮播图新"]];

    _cycleScrollView.autoScrollTimeInterval = 5.;// 自动滚动时间间隔
    _cycleScrollView.delegate=self;
    _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;// 翻页 右下角
    _cycleScrollView.pageControlAliment= SDCycleScrollViewPageContolAlimentCenter;
//    _cycleScrollView.pageControlBottomOffset=-20;
    _cycleScrollView.pageControlDotSize = CGSizeMake(7, 2);
    
    _cycleScrollView.pageDotColor=[CommonClass colorWithHexString:@"#cecece"];
    _cycleScrollView.currentPageDotColor=[CommonClass colorWithHexString:@"#191919"];
    _cycleScrollView.pageControlStyle=SDCycleScrollViewPageContolStyleAnimated;
//     ok xib 自动布局都可以。还是很不错的。
//    [SDCycleScrollView clearImagesCache];// 清除缓存。
    [backView addSubview:_cycleScrollView];
    _cycleScrollView.sd_layout
    .leftEqualToView(backView)
    .topEqualToView(backView)
    .rightEqualToView(backView)
    .bottomEqualToView(backView);
    
    self.tableView.tableHeaderView = topView;
    
//    [self.view addSubview:self.mineCenterBtn];
//    self.mineCenterBtn.sd_layout.leftEqualToView(self.view).offset(22).topEqualToView(topView).offset(30).widthIs(22).heightIs(22);
}
- (void)loadMatchSocket{
    [LSHttpEnclosureTool GET:LSWebSocketGetUrl parameters:@{@"type":@"5",@"h":@"大厅"} resBlock:^(id responseObject) {
//        MyLog(@"HotMatchSocket-----%@",responseObject);
        if ([CommonClass isBlankString:responseObject] == NO) {
            [manager ls_open:responseObject connect:^{
                
            } receive:^(id message, LSSocketReceiveType type) {
                
                if ([message isEqualToString:@"websocket connected!"]) {
                }else{
//                    MyLog(@"2 --- %@",message);
                    self.matchSocketArray = message;
                    
                }
            } failure:^(NSError *error) {
                MyLog(@"%@",error);
            }];
        }
    }];
}
- (void)loadSectionData{
//    [self.sectionArray removeAllObjects];
    [LSHttpEnclosureTool GET:LSIndexMenu parameters:nil resBlock:^(id responseObject) {
        if (responseObject) {
            
            self.sectionArray = responseObject;
            MyLog(@"IndexMenu --- %@",self.sectionArray);
        }
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
//        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
    }];

}
- (void)loadHotMatchData{
    [self.hotMatchArray removeAllObjects];
    [LSHttpEnclosureTool GET:LSHOTMATCH parameters:nil resBlock:^(id responseObject) {
        if (responseObject) {
            MyLog(@"HotMatch --- %@",responseObject);
            [self.hotMatchArray addObjectsFromArray:responseObject[@"MatchList"]];
            [self loadMatchSocket];
        }
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
//        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
    }];
    
}
- (void)loadData:(BOOL)refresh{
    if (refresh) {
        
        self.pageIndex = 0;
    }else{
        
        self.pageIndex += 1;
    }
    NSDictionary *articlehotDic = @{@"type":@(self.queryType),@"pageIndex":@(self.pageIndex)};
    [LSHttpEnclosureTool GET:LSArticleHot parameters:articlehotDic resBlock:^(id responseObject) {
        if (responseObject) {
            if (refresh) {
                [self.modelArray removeAllObjects];
            }
            LSHomeArticleHotModel *model=[LSHomeArticleHotModel mj_objectWithKeyValues:responseObject];
            [self.modelArray addObjectsFromArray:model.ArticleQueryList];
            
            
        }else{
            
            self.pageIndex -= 1;
            
        }
        [CommonClass endRefreshing:self.tableView];
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
//        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
    }];
    
    
    
}

-(void)requestBannerData{


    [LSHttpEnclosureTool GET:LSBanner parameters:@{@"type":@"10"} resBlock:^(id responseObject) {
        if (responseObject) {
            NSMutableArray *imageArr = [NSMutableArray array];
            self.bannerArray = responseObject[@"BannerList"];
            
            for (NSDictionary *dic in responseObject[@"BannerList"]) {
                [imageArr addObject:dic[@"ImageUrl"]];
            }
            _cycleScrollView.imageURLStringsGroup = imageArr;
        }
    }];
}

#pragma mark - ScrollViewDelegate
//监听页面滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offset = scrollView.contentOffset.y;
   
    
    if (offset > NAVBAR_COLORCHANGE_POINT){
        
        CGFloat alpha = (offset - NAVBAR_COLORCHANGE_POINT) / NAV_HEIGHT;
        [self wr_setNavBarBackgroundAlpha:alpha];
        [self wr_setStatusBarStyle:UIStatusBarStyleDefault];
        self.title = @"首页";
        [self.tabBarItem setTitle:@"首页"];
    }else{
        [self wr_setNavBarBackgroundAlpha:0];
        [self wr_setStatusBarStyle:UIStatusBarStyleLightContent];
        self.title = @"";
        [self.tabBarItem setTitle:@"首页"];
    }
    
    
    
}
#pragma mark 🔥 tableViewDelegate tableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==0) {
        
        return 1;
    }
    if (section==1) {

        return self.hotMatchArray.count;
    }
    return  self.modelArray.count;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (indexPath.section==0) {
        
        return 100;
    }
    if (indexPath.section==1) {
        
        return 85;
    }
    return 114;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section==1) {
        if (self.hotMatchArray.count!=0) {
            LSCustomHeaderView * headerView=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HomeMatchHotView"];
            if (!headerView) {
                
                headerView=[[LSCustomHeaderView alloc]initWithReuseIdentifier:@"HomeMatchHotView" style:KTableViewHeaderScrollerStyle];
                [headerView  setScrolArray:@[@"热门赛事"] spaceWidth:30 titleColor:[CommonClass colorWithHexString:@"#838383"] seletedColor:LSSubColor75b8fe with:_tag];
                headerView.contentView.backgroundColor=[UIColor whiteColor];
                headerView.lineColor=LSSubColor5cd2df;
                headerView.acrossView.hidden = YES;
                headerView.butonActionBlock = ^(NSInteger tag) {
                    self.queryType=tag;
                    [self loadData:YES];
                    
                };
            }
            return headerView;
        }else{
            UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
            headerView.backgroundColor = [UIColor whiteColor];
            return headerView;
        }
    }
    if (section==2) {
        
        LSCustomHeaderView * headerView=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HomeRecommendHotView"];
        if (!headerView) {
            
            headerView=[[LSCustomHeaderView alloc]initWithReuseIdentifier:@"HomeRecommendHotView" style:KTableViewHeaderScrollerStyle];
            [headerView  setScrolArray:@[@"推荐",@"热门",@"资讯"] spaceWidth:30 titleColor:[CommonClass colorWithHexString:@"#191919"] seletedColor:LSSubColore5735e with:_tag];
            headerView.contentView.backgroundColor=[UIColor whiteColor];
            headerView.lineColor=LSSubColore5735e;
            headerView.butonActionBlock = ^(NSInteger tag) {
                self.queryType=tag;
                [self loadData:YES];
                
                _tag = tag;
            };
        }
        
       
        return headerView;
    }
    return nil;
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1||section==2) {
        if (section==1) {
            if (self.hotMatchArray.count==0) {
                return 0;
            }
        }
        return 42;
    }
    return 0;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        LSHomeSectionChooseCell *cell=[LSHomeSectionChooseCell HomeSectionChooseTableViewCellBytableView:tableView];
        cell.arrayT = self.sectionArray;
        cell.buttonTargetEventBlock = ^(NSString *buttonTitle) {
            [self jumpDetailOrchooseMoreEvent:buttonTitle];
        };
        return cell;
      
    }
    else if(indexPath.section==1){
        LSHomeHotMatchCell *cell=[LSHomeHotMatchCell HomeHotMatchCellByTableView:tableView];
        LSHomeHotMatchModel *hotMatchModel = [LSHomeHotMatchModel mj_objectWithKeyValues:self.hotMatchArray[indexPath.row]];
//        LSHomeSocketModel *socketModel = [LSHomeSocketModel mj_objectWithKeyValues:self.matchSocketArray[indexPath.row]];
        cell.hotMatchModel = hotMatchModel;
//        cell.socketModel = socketModel;
        return cell;
    }
    else if(indexPath.section==2){
        LSHomeSectionCell *cell=[LSHomeSectionCell HomeSectionTableViewCellBytableView:tableView];
        cell.listModel=self.modelArray[indexPath.row];
        return cell;
    }else{
        
        return [UITableViewCell new];
    }
   
//    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==2) {
        LSHomeSectionCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        LSHomeArticleDetailVController *articleVC=[[LSHomeArticleDetailVController alloc]init];
        articleVC.articleId=cell.listModel.Id;
        [self.navigationController pushViewController:articleVC animated:YES];
        
    }else if (indexPath.section == 1){
        LSHomeHotMatchModel *model = [LSHomeHotMatchModel mj_objectWithKeyValues:self.hotMatchArray[indexPath.row]];
        
        LSLiveCompetitionViewController *liveCompetitionVC = [[LSLiveCompetitionViewController alloc] init];
//        liveCompetitionVC.guestId = [model.Guest integerValue];
//        liveCompetitionVC.homeId = [model.HomeTeamId integerValue];
//        liveCompetitionVC.leagueId = model.LeagueId;
        liveCompetitionVC.matchId = model.MatchId;
        liveCompetitionVC.selectIndex = 2;
        [self.navigationController pushViewController:liveCompetitionVC animated:YES];
        
        
    }
   
}

#pragma mark 🔥 buttonTarget
//- (void)clickMineCenterButton{
//    LSMineVController *loginVC=[[LSMineVController alloc]init];
//
////    [self cw_showDefaultDrawerViewController:loginVC];
//}
#pragma mark 🔥 choose事件
-(void)jumpDetailOrchooseMoreEvent:(NSString *)title{
    MyLog(@"title --- %@",title);
    if ([title isEqualToString:@"资料库"]) {
//        [MBProgressHUD showOnlyMessage:@"正在建设中。。。" afterDelay:1.5f];
        LSDataBankVController *dataBankVC = [[LSDataBankVController alloc] init];
        dataBankVC.title = title;
        [self.navigationController pushViewController:dataBankVC animated:YES];
    }
    if ([title isEqualToString:@"专家排行"]){
        LSExpertRankBaseViewController * expertRankVC = [[LSExpertRankBaseViewController alloc] init];
        expertRankVC.title = title;
        [self.navigationController pushViewController:expertRankVC animated:YES];
        
    }else if ([title isEqualToString:@"足球百科"]){
        LSPlayTricksViewController * playTricksVC = [[LSPlayTricksViewController alloc] init];
        playTricksVC.title = title;
        [self.navigationController pushViewController:playTricksVC animated:YES];
    }else if ([title isEqualToString:@"热门话题"]){
//        LSHotTopicViewController * hotTopicVC = [[LSHotTopicViewController alloc] init];
//        [self.navigationController pushViewController:hotTopicVC animated:YES];
        
        [self getHotTopicWithTitle:title];

    }
    
//    else if ([title isEqualToString:@""]){
//        
//        NSArray *FunctionArray=@[@[@"HomeSMG",@"竞彩"],@[@"HomeBJSingle",@"北单"],@[@"HomeGrounderR",@"滚球"],@[@"HomeDataBank",@"资料库"],@[@"HomeSMG",@"竞彩l"]];
//        NSArray *selectedArray=@[@"竞彩",@"北单",@"滚球",@"资料库"];
//        [LSHomeCustomFunctionView  addChooseFunctionArray:FunctionArray selectedArray:selectedArray view:self.view againChooseBlock:^(NSMutableArray *array) {
//            
//        }];
//      
//    }
    
}

#pragma mark 🔥 查询热门话题
- (void)getHotTopicWithTitle:(NSString *)title{
    [LSHttpEnclosureTool GET:LSSysConfig parameters:@{@"key":@"App.Index.HotTopicId"} resBlock:^(id responseObject) {
        if (responseObject) {
            MyLog(@"SysConfig --- %@",responseObject);
            LSHotTopicViewController * hotTopicVC = [[LSHotTopicViewController alloc] init];
            
            hotTopicVC.TopicId = [responseObject[@"ConfigValue"] integerValue];
            hotTopicVC.cid = [LSAccountArchive isLogin] ? [LSAccountArchive account].Cid : @"";
            hotTopicVC.title = title;
            [self.navigationController pushViewController:hotTopicVC animated:YES];
        }
    }];
}
#pragma mark 🔥 cycleScrollViewDelegate
/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    MyLog(@"url --- %@",self.bannerArray[index][@"LinkUrl"]);
//    [LSHttpEnclosureTool  GET:LSWebSocketGetUrl parameters:@{@"type":@"h"} resBlock:^(id responseObject) {
//        if (responseObject) {
//
//        }
//    }];
}
#pragma mark 🔥 navigation Event

//-(void)addMineViewBySwipeGesture:(UISwipeGestureRecognizer *)recognizer{
//    // 注册手势驱动
//
//}
//
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
//    // 点击的view的类名
//    MyLog(@"%@", NSStringFromClass([touch.view class]));
//    // 点击了tableViewCell，view的类名为UITableViewCellContentView，则不接收Touch点击事件
//    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
//        return NO;
//    }
//    return  YES;
//}
//
//
//- (void)drawerDefaultAnimationRight{
////    LSMineVController *vc = [[LSMineVController alloc] init];
////    CWLateralSlideConfiguration *conf = [CWLateralSlideConfiguration defaultConfiguration];
////    conf.direction = CWDrawerTransitionFromRight; // 从右边滑出
////    conf.finishPercent = 0.2f;
////    conf.showAnimDuration = 0.2;
////    conf.HiddenAnimDuration = 0.2;
////    conf.maskAlpha = 0.1;
////
////    [self cw_showDrawerViewController:vc animationType:CWDrawerAnimationTypeDefault configuration:conf];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
